package minidb.drive;

import static minidb.type.Const.*;
import minidb.buffer.Buffer;
import minidb.index.*;
import minidb.record.*;

public class IndexOp
{
	public void CreateIndex(String indexName,String tableName,String fieldName, int isOnly)
	{
		TableInfo tab = tablePage.get(tableName);
		while(true){
			synchronized(tab.lock){
				if(tab.ID < 0 || Thread.currentThread().getId() == tab.ID)
					break;
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		RecordPage rec = new RecordPage(tab);
		bTreeIndex index = new bTreeIndex(tab, rec);
		try{
			index.index(fieldName);	
			throw new RuntimeException("INDEX HAS ALREADY EXIST: " + indexName);
		}catch(Exception e){
			try{
				index.CreatIndex(indexName,fieldName, isOnly);
			}catch(Exception o){
				throw new RuntimeException (o.getMessage());
			}
		}
		index.close();
	}
	
	public void DropIndex(String indexName)
	{
		TableInfo tab = null;
		RecordPage rec = null;
		bTreeIndex index = null;
		try{
			int pageNum = new indexHeader().getIndex(indexName);			
			if(pageNum == 0){
				throw new RuntimeException("NO SUCH INDEX: "+ indexName);
			}
			int prev = 0;
			Buffer buf = bufpool.pin(pageNum);
			while(buf.getInt(PRE_PAGE)!=0){
				prev = buf.getInt(PRE_PAGE);
				bufpool.unpin(buf);
				buf = bufpool.pin(prev);
			}
			prev = buf.pageNum();
			for(TableInfo tmp: tablePage.table.values()){
				if(tmp.indexPage()==prev){
					tab = tmp;
					break;
				}
			}
			rec = new RecordPage(tab);
			index = new bTreeIndex(tab, rec);
			index.DeleteIndex(pageNum);
			new indexHeader().deleteIndex(pageNum);
		}catch(Exception e){
			throw new RuntimeException (e.getMessage());
		}
		index.close();
	}
}
